<!DOCTYPE html>




<html class="theme-next gemini" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
    
  
  <link href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|Source Code Pro:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="https://cdn.staticfile.org/font-awesome/4.6.2/css/font-awesome.css" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=6.0.0" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="icon" type="image/png" sizes="32x32" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="icon" type="image/png" sizes="16x16" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0">


  <link rel="mask-icon" href="http://tva3.sinaimg.cn/crop.206.47.515.515.180/709d5819jw8f4k1tlmnsij20pr0gytdx.jpg?v=6.0.0" color="#222">





  <meta name="keywords" content="vps, java, python, golang, springmvc">




  


  <link rel="alternate" href="/atom.xml" title="张恒的网络日志" type="application/atom+xml">






<meta name="keywords" content="java, python, go, 技术, 学习笔记, spring">
<meta property="og:type" content="website">
<meta property="og:title" content="张恒的网络日志">
<meta property="og:url" content="http://blog.gavinzh.com/404.html">
<meta property="og:site_name" content="张恒的网络日志">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-01-05T08:52:36.912Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="张恒的网络日志">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.0.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    fastclick: true,
    lazyload: true,
    tabs: true,
    motion: {"enable":false,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.gavinzh.com/404.html">





  <title>SpringMVC 解毒2 | 张恒的网络日志</title>
  




<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-98061925-1', 'auto');
  ga('send', 'pageview');
</script>





</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> <div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">张恒的网络日志</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">Zhang Heng's WebSite Blog</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.gavinzh.com/2018/08/12/learn-springmvc-code-2/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Gavin Zhang">
      <meta itemprop="description" content>
      <meta itemprop="image" content="https://avatars3.githubusercontent.com/u/5567916">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="张恒的网络日志">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">SpringMVC 解毒2</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-08-12T08:36:00+00:00">2018-08-12</time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/笔记/" itemprop="url" rel="index">
                    <span itemprop="name">笔记</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2018/08/12/learn-springmvc-code-2/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count" data-disqus-identifier="2018/08/12/learn-springmvc-code-2/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/2018/08/12/learn-springmvc-code-2/" class="leancloud_visitors" data-flag-title="SpringMVC 解毒2">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="3-HandlerMapping"><a href="#3-HandlerMapping" class="headerlink" title="3 HandlerMapping"></a>3 HandlerMapping</h2><img src="http://www.plantuml.com/plantuml/svg/dLJBJiCm4BpxAwmSaMA9EqBY9T43FO3uWAspUQY9RMotHGB-dQHk825sOff3OcLtnZkpNXC5V0i5KgaBPfIkH95hQF0WzPOTSCCCwdsDbduGGjkd4XPr3Xpf8uYiHlq4IhMWOz2ViUf-S5HMQiV1Qp2cZpwy8z_PIegx4YhnI-CDq-GoeHTfUasJTUBZxz1VX4IAOgLZwCLHs1YhWLjwSrfuHDBXEmX0MyhC0vi0NdKTtiGvzL8rgiRPn0djFLhajisQXGrtkKKGwzQaY8Aw06P_V6zJt6UCfbUVQHhjfp-F-ab27aUHHFWIJ7LC4MrPO3YdMSiOnntLpka4EN2emNFsHepcMCb_1hNPSzOS-ztFwi-9VyQt7HfxAcCbSXcwcOYl-k4XSkBZ2C-hde4Gqa9teVL2t4YDDmqfM2hD9y37rTR-3G00">

<p>图3-1</p>
<a id="more"></a>

<p>在第2章，<code>DipatcherServlet</code>中使用 HandlerMapping 得到执行链<code>HandlerExecutionChain</code>，然后就再也没有 HandlerMapping 的事了。也就是说SpringMVC就是靠 HandlerMapping 通过入参 HttpServletRequest 判断应该调用哪个方法、或者返回哪个文件，所以就让我们从这里入手。</p>
<h3 id="3-1-HandlerExecutionChain-对象"><a href="#3-1-HandlerExecutionChain-对象" class="headerlink" title="3.1 HandlerExecutionChain 对象"></a>3.1 HandlerExecutionChain 对象</h3><img src="http://www.plantuml.com/plantuml/svg/fP2nJWCn38RtF8KbbYALH-XGLPNAW41KOgaOqiIz2qhjuFYkXn3lJhWS81Q4Q8OuqV_RdstZeiqPDfPyH5aFw3eDJAlM1e9N0-MCrzMdvPeKnM5IbjqZXEzVddo7G3R2xVu9dK9RaqPfiHZ31UoP8re2cr9ykHEibMSRrRH5wIFgFJvtc1ManZdyq79YobZ4-hW4ROLF6TR3HoUb-udJS_0JXBEUIPd33NkCI_8F0Kzmx7_7geIcGLaUodvMV4obP76SGV-Y00v_c7W2a-j4aEhmWPgjMb7q_z-rCM_c7G00">

<p>这个对象很简单，没有继承，没有子类。<code>DipatcherServlet</code>中用到了，HandlerMapping 也用到了，所以必须提一下。其中Object的handler就是具体处理器，interceptors会在handler执行前后以及整个请求处理完后调用。</p>
<p>HandlerInterceptor 是什么这里简单介绍一下，它是一个接口，还记得在第2章讲执行链调用预处理方法、后处理方法和完成触发方法吗？调用的就是这个接口的对应方法。MappedInterceptor 是 HandlerInterceptor 接口的继承接口，它的作用包装一个 HandlerInterceptor 并且可以设置上URI规则，允许调用接口方法前先判断是否符合规则。其他的 HandlerInterceptor 实现类目前就先不介绍了。</p>
<p>其中前三个主要方法各有特色，我就分别来讲讲。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Apply preHandle methods of registered interceptors.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> &#123;<span class="doctag">@code</span> true&#125; if the execution chain should proceed with the</span></span><br><span class="line"><span class="comment"> * next interceptor or the handler itself. Else, DispatcherServlet assumes</span></span><br><span class="line"><span class="comment"> * that this interceptor has already dealt with the response itself.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">boolean</span> <span class="title">applyPreHandle</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    HandlerInterceptor[] interceptors = getInterceptors();</span><br><span class="line">    <span class="keyword">if</span> (!ObjectUtils.isEmpty(interceptors)) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; interceptors.length; i++) &#123;</span><br><span class="line">            HandlerInterceptor interceptor = interceptors[i];</span><br><span class="line">            <span class="keyword">if</span> (!interceptor.preHandle(request, response, <span class="keyword">this</span>.handler)) &#123;</span><br><span class="line">                triggerAfterCompletion(request, response, <span class="keyword">null</span>);</span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">this</span>.interceptorIndex = i;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>预处理（前处理）方法大家请看，for循环是从小到大的，还记录了拦截器的下标，当有一个拦截器返回false时，会调用完成触发方法 triggerAfterCompletion。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Apply postHandle methods of registered interceptors.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">applyPostHandle</span><span class="params">(HttpServletRequest request, HttpServletResponse response, ModelAndView mv)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    HandlerInterceptor[] interceptors = getInterceptors();</span><br><span class="line">    <span class="keyword">if</span> (!ObjectUtils.isEmpty(interceptors)) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = interceptors.length - <span class="number">1</span>; i &gt;= <span class="number">0</span>; i--) &#123;</span><br><span class="line">            HandlerInterceptor interceptor = interceptors[i];</span><br><span class="line">            interceptor.postHandle(request, response, <span class="keyword">this</span>.handler, mv);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>后处理方法和前处理方法区别在for循环是从大往小的。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Trigger afterCompletion callbacks on the mapped HandlerInterceptors.</span></span><br><span class="line"><span class="comment"> * Will just invoke afterCompletion for all interceptors whose preHandle invocation</span></span><br><span class="line"><span class="comment"> * has successfully completed and returned true.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">triggerAfterCompletion</span><span class="params">(HttpServletRequest request, HttpServletResponse response, Exception ex)</span></span></span><br><span class="line"><span class="function">        <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    HandlerInterceptor[] interceptors = getInterceptors();</span><br><span class="line">    <span class="keyword">if</span> (!ObjectUtils.isEmpty(interceptors)) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="keyword">this</span>.interceptorIndex; i &gt;= <span class="number">0</span>; i--) &#123;</span><br><span class="line">            HandlerInterceptor interceptor = interceptors[i];</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                interceptor.afterCompletion(request, response, <span class="keyword">this</span>.handler, ex);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">catch</span> (Throwable ex2) &#123;</span><br><span class="line">                logger.error(<span class="string">"HandlerInterceptor.afterCompletion threw exception"</span>, ex2);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>完成触发方法更奇葩，for循环从大往小不说，还从记录的下标开始。什么意思呢？就是说如果执行到第index+1个预处理方法返回了false，就从第index个拦截器倒着往回执行完成触发方法。</p>
<p>最后一个方法是针对Servlet3.0标准中的异步处理设置的，这里就先不讲了。</p>
<h3 id="3-2-HandlerMapping接口分析"><a href="#3-2-HandlerMapping接口分析" class="headerlink" title="3.2 HandlerMapping接口分析"></a>3.2 HandlerMapping接口分析</h3><p>HandlerMapping 接口非常简单，就一个方法，从 HttpServletRequest 获取一个执行链<code>HandlerExecutionChain</code>，如果没有映射上的handler，就应该返回null。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Interface to be implemented by objects that define a mapping between</span></span><br><span class="line"><span class="comment"> * requests and handler objects.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;This class can be implemented by application developers, although this is not</span></span><br><span class="line"><span class="comment"> * necessary, as &#123;<span class="doctag">@link</span> org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping&#125;</span></span><br><span class="line"><span class="comment"> * and &#123;<span class="doctag">@link</span> org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping&#125;</span></span><br><span class="line"><span class="comment"> * are included in the framework. The former is the default if no</span></span><br><span class="line"><span class="comment"> * HandlerMapping bean is registered in the application context.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;HandlerMapping implementations can support mapped interceptors but do not</span></span><br><span class="line"><span class="comment"> * have to. A handler will always be wrapped in a &#123;<span class="doctag">@link</span> HandlerExecutionChain&#125;</span></span><br><span class="line"><span class="comment"> * instance, optionally accompanied by some &#123;<span class="doctag">@link</span> HandlerInterceptor&#125; instances.</span></span><br><span class="line"><span class="comment"> * The DispatcherServlet will first call each HandlerInterceptor's</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@code</span> preHandle&#125; method in the given order, finally invoking the handler</span></span><br><span class="line"><span class="comment"> * itself if all &#123;<span class="doctag">@code</span> preHandle&#125; methods have returned &#123;<span class="doctag">@code</span> true&#125;.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;The ability to parameterize this mapping is a powerful and unusual</span></span><br><span class="line"><span class="comment"> * capability of this MVC framework. For example, it is possible to write</span></span><br><span class="line"><span class="comment"> * a custom mapping based on session state, cookie state or many other</span></span><br><span class="line"><span class="comment"> * variables. No other MVC framework seems to be equally flexible.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;Note: Implementations can implement the &#123;<span class="doctag">@link</span> org.springframework.core.Ordered&#125;</span></span><br><span class="line"><span class="comment"> * interface to be able to specify a sorting order and thus a priority for getting</span></span><br><span class="line"><span class="comment"> * applied by DispatcherServlet. Non-Ordered instances get treated as lowest priority.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> Rod Johnson</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> Juergen Hoeller</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> org.springframework.core.Ordered</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> org.springframework.web.servlet.handler.AbstractHandlerMapping</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">HandlerMapping</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Name of the &#123;<span class="doctag">@link</span> HttpServletRequest&#125; attribute that contains the path</span></span><br><span class="line"><span class="comment">     * within the handler mapping, in case of a pattern match, or the full</span></span><br><span class="line"><span class="comment">     * relevant URI (typically within the DispatcherServlet's mapping) else.</span></span><br><span class="line"><span class="comment">     * &lt;p&gt;Note: This attribute is not required to be supported by all</span></span><br><span class="line"><span class="comment">     * HandlerMapping implementations. URL-based HandlerMappings will</span></span><br><span class="line"><span class="comment">     * typically support it, but handlers should not necessarily expect</span></span><br><span class="line"><span class="comment">     * this request attribute to be present in all scenarios.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    String PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE = HandlerMapping.class.getName() + ".pathWithinHandlerMapping";</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Name of the &#123;<span class="doctag">@link</span> HttpServletRequest&#125; attribute that contains the</span></span><br><span class="line"><span class="comment">     * best matching pattern within the handler mapping.</span></span><br><span class="line"><span class="comment">     * &lt;p&gt;Note: This attribute is not required to be supported by all</span></span><br><span class="line"><span class="comment">     * HandlerMapping implementations. URL-based HandlerMappings will</span></span><br><span class="line"><span class="comment">     * typically support it, but handlers should not necessarily expect</span></span><br><span class="line"><span class="comment">     * this request attribute to be present in all scenarios.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    String BEST_MATCHING_PATTERN_ATTRIBUTE = HandlerMapping.class.getName() + ".bestMatchingPattern";</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Name of the boolean &#123;<span class="doctag">@link</span> HttpServletRequest&#125; attribute that indicates</span></span><br><span class="line"><span class="comment">     * whether type-level mappings should be inspected.</span></span><br><span class="line"><span class="comment">     * &lt;p&gt;Note: This attribute is not required to be supported by all</span></span><br><span class="line"><span class="comment">     * HandlerMapping implementations.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    String INTROSPECT_TYPE_LEVEL_MAPPING = HandlerMapping.class.getName() + ".introspectTypeLevelMapping";</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Name of the &#123;<span class="doctag">@link</span> HttpServletRequest&#125; attribute that contains the URI</span></span><br><span class="line"><span class="comment">     * templates map, mapping variable names to values.</span></span><br><span class="line"><span class="comment">     * &lt;p&gt;Note: This attribute is not required to be supported by all</span></span><br><span class="line"><span class="comment">     * HandlerMapping implementations. URL-based HandlerMappings will</span></span><br><span class="line"><span class="comment">     * typically support it, but handlers should not necessarily expect</span></span><br><span class="line"><span class="comment">     * this request attribute to be present in all scenarios.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    String URI_TEMPLATE_VARIABLES_ATTRIBUTE = HandlerMapping.class.getName() + ".uriTemplateVariables";</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Name of the &#123;<span class="doctag">@link</span> HttpServletRequest&#125; attribute that contains a map with</span></span><br><span class="line"><span class="comment">     * URI matrix variables.</span></span><br><span class="line"><span class="comment">     * &lt;p&gt;Note: This attribute is not required to be supported by all</span></span><br><span class="line"><span class="comment">     * HandlerMapping implementations and may also not be present depending on</span></span><br><span class="line"><span class="comment">     * whether the HandlerMapping is configured to keep matrix variable content</span></span><br><span class="line"><span class="comment">     * in the request URI.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    String MATRIX_VARIABLES_ATTRIBUTE = HandlerMapping.class.getName() + ".matrixVariables";</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Name of the &#123;<span class="doctag">@link</span> HttpServletRequest&#125; attribute that contains the set of</span></span><br><span class="line"><span class="comment">     * producible MediaTypes applicable to the mapped handler.</span></span><br><span class="line"><span class="comment">     * &lt;p&gt;Note: This attribute is not required to be supported by all</span></span><br><span class="line"><span class="comment">     * HandlerMapping implementations. Handlers should not necessarily expect</span></span><br><span class="line"><span class="comment">     * this request attribute to be present in all scenarios.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    String PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE = HandlerMapping.class.getName() + ".producibleMediaTypes";</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Return a handler and any interceptors for this request. The choice may be made</span></span><br><span class="line"><span class="comment">     * on request URL, session state, or any factor the implementing class chooses.</span></span><br><span class="line"><span class="comment">     * &lt;p&gt;The returned HandlerExecutionChain contains a handler Object, rather than</span></span><br><span class="line"><span class="comment">     * even a tag interface, so that handlers are not constrained in any way.</span></span><br><span class="line"><span class="comment">     * For example, a HandlerAdapter could be written to allow another framework's</span></span><br><span class="line"><span class="comment">     * handler objects to be used.</span></span><br><span class="line"><span class="comment">     * &lt;p&gt;Returns &#123;<span class="doctag">@code</span> null&#125; if no match was found. This is not an error.</span></span><br><span class="line"><span class="comment">     * The DispatcherServlet will query all registered HandlerMapping beans to find</span></span><br><span class="line"><span class="comment">     * a match, and only decide there is an error if none can find a handler.</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> request current HTTP request</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> a HandlerExecutionChain instance containing handler object and</span></span><br><span class="line"><span class="comment">     * any interceptors, or &#123;<span class="doctag">@code</span> null&#125; if no mapping found</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> Exception if there is an internal error</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function">HandlerExecutionChain <span class="title">getHandler</span><span class="params">(HttpServletRequest request)</span> <span class="keyword">throws</span> Exception</span>;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>接口虽简单，但是要注意其中的一些常量。</p>
<ul>
<li><code>PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE</code>: 这个常量会被放到request的属性中，用来设置SpringMVC用的URI地址。</li>
<li><code>BEST_MATCHING_PATTERN_ATTRIBUTE</code>: 这个常量会被放到request的属性中，用来设置匹配到的最合适的URI。</li>
<li><code>INTROSPECT_TYPE_LEVEL_MAPPING</code>: 这个常量目前来说没用。</li>
<li><code>URI_TEMPLATE_VARIABLES_ATTRIBUTE</code>: 这个常量会被放到request的属性中，用于存放临时变量，在使用restfull风格的uri时会用到。</li>
<li><code>MATRIX_VARIABLES_ATTRIBUTE</code>: URI标准中有一种参数叫做矩阵参数，例如aaa/bbb;a=1;b=c。这个常量会被放到request的属性中，当有矩阵参数时，矩阵参数的解析结果将放到这里。</li>
<li><code>PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE</code>:这个常量会被放到request的属性中，会将映射上的处理器能产生的media type类型放到这里。</li>
</ul>
<h3 id="3-3-AbstractHandlerMapping-解析"><a href="#3-3-AbstractHandlerMapping-解析" class="headerlink" title="3.3 AbstractHandlerMapping 解析"></a>3.3 AbstractHandlerMapping 解析</h3><p>在图3-1上，我们看到 HandlerMapping 的唯一直接实现类是 AbstractHandlerMapping ，那我们就从 AbstractHandlerMapping 开始看吧。</p>
<h4 id="3-3-1-AbstractHandlerMapping-初始化解析"><a href="#3-3-1-AbstractHandlerMapping-初始化解析" class="headerlink" title="3.3.1 AbstractHandlerMapping 初始化解析"></a>3.3.1 AbstractHandlerMapping 初始化解析</h4><p>别看这个类属性那么多，还继承了你不知道的类。根据之前的经验，初始化部分，只要你看到这个类里有重写父类的方法，带有init类似字段，那这个方法保准是初始化方法。</p>
<p>按照这个道理，我们顺理成章地找到了下面这些方法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Initializes the interceptors.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #extendInterceptors(java.util.List)</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #initInterceptors()</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">initApplicationContext</span><span class="params">()</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">    extendInterceptors(<span class="keyword">this</span>.interceptors);</span><br><span class="line">    detectMappedInterceptors(<span class="keyword">this</span>.adaptedInterceptors);</span><br><span class="line">    initInterceptors();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Detect beans of type &#123;<span class="doctag">@link</span> MappedInterceptor&#125; and add them to the list of mapped interceptors.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;This is called in addition to any &#123;<span class="doctag">@link</span> MappedInterceptor&#125;s that may have been provided</span></span><br><span class="line"><span class="comment"> * via &#123;<span class="doctag">@link</span> #setInterceptors&#125;, by default adding all beans of type &#123;<span class="doctag">@link</span> MappedInterceptor&#125;</span></span><br><span class="line"><span class="comment"> * from the current context and its ancestors. Subclasses can override and refine this policy.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> mappedInterceptors an empty list to add &#123;<span class="doctag">@link</span> MappedInterceptor&#125; instances to</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">detectMappedInterceptors</span><span class="params">(List&lt;HandlerInterceptor&gt; mappedInterceptors)</span> </span>&#123;</span><br><span class="line">    mappedInterceptors.addAll(</span><br><span class="line">            BeanFactoryUtils.beansOfTypeIncludingAncestors(</span><br><span class="line">                    getApplicationContext(), MappedInterceptor<span class="class">.<span class="keyword">class</span>, <span class="title">true</span>, <span class="title">false</span>).<span class="title">values</span>())</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Initialize the specified interceptors, checking for &#123;<span class="doctag">@link</span> MappedInterceptor&#125;s and</span></span><br><span class="line"><span class="comment"> * adapting &#123;<span class="doctag">@link</span> HandlerInterceptor&#125;s and &#123;<span class="doctag">@link</span> WebRequestInterceptor&#125;s if necessary.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #setInterceptors</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #adaptInterceptor</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">initInterceptors</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!<span class="keyword">this</span>.interceptors.isEmpty()) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="keyword">this</span>.interceptors.size(); i++) &#123;</span><br><span class="line">            Object interceptor = <span class="keyword">this</span>.interceptors.get(i);</span><br><span class="line">            <span class="keyword">if</span> (interceptor == <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"Entry number "</span> + i + <span class="string">" in interceptors array is null"</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">this</span>.adaptedInterceptors.add(adaptInterceptor(interceptor));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Adapt the given interceptor object to the &#123;<span class="doctag">@link</span> HandlerInterceptor&#125; interface.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;By default, the supported interceptor types are &#123;<span class="doctag">@link</span> HandlerInterceptor&#125;</span></span><br><span class="line"><span class="comment"> * and &#123;<span class="doctag">@link</span> WebRequestInterceptor&#125;. Each given &#123;<span class="doctag">@link</span> WebRequestInterceptor&#125;</span></span><br><span class="line"><span class="comment"> * will be wrapped in a &#123;<span class="doctag">@link</span> WebRequestHandlerInterceptorAdapter&#125;.</span></span><br><span class="line"><span class="comment"> * Can be overridden in subclasses.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> interceptor the specified interceptor object</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the interceptor wrapped as HandlerInterceptor</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> org.springframework.web.servlet.HandlerInterceptor</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> org.springframework.web.context.request.WebRequestInterceptor</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> WebRequestHandlerInterceptorAdapter</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> HandlerInterceptor <span class="title">adaptInterceptor</span><span class="params">(Object interceptor)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (interceptor <span class="keyword">instanceof</span> HandlerInterceptor) &#123;</span><br><span class="line">        <span class="keyword">return</span> (HandlerInterceptor) interceptor;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span> (interceptor <span class="keyword">instanceof</span> WebRequestInterceptor) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> WebRequestHandlerInterceptorAdapter((WebRequestInterceptor) interceptor);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"Interceptor type not supported: "</span> + interceptor.getClass().getName());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这些方法做了一件事，就是在web应用上下文创建完成后，从上下文中找到 MappedInterceptor 并且和 自身属性 interceptors 做融合，设置到属性 adaptedInterceptors 中。</p>
<h4 id="3-3-2-AbstractHandlerMapping-执行请求分析"><a href="#3-3-2-AbstractHandlerMapping-执行请求分析" class="headerlink" title="3.3.2 AbstractHandlerMapping 执行请求分析"></a>3.3.2 AbstractHandlerMapping 执行请求分析</h4><p>AbstractHandlerMapping 是一个抽象类，所以它应该还会把具体的获取handler交给它的子类。那他在这里会做什么呢？来看代码吧</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Look up a handler for the given request, falling back to the default</span></span><br><span class="line"><span class="comment"> * handler if no specific one is found.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> request current HTTP request</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the corresponding handler instance, or the default handler</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #getHandlerInternal</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> HandlerExecutionChain <span class="title">getHandler</span><span class="params">(HttpServletRequest request)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    Object handler = getHandlerInternal(request);</span><br><span class="line">    <span class="keyword">if</span> (handler == <span class="keyword">null</span>) &#123;</span><br><span class="line">        handler = getDefaultHandler();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (handler == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// Bean name or resolved handler?</span></span><br><span class="line">    <span class="keyword">if</span> (handler <span class="keyword">instanceof</span> String) &#123;</span><br><span class="line">        String handlerName = (String) handler;</span><br><span class="line">        handler = getApplicationContext().getBean(handlerName);</span><br><span class="line">    &#125;</span><br><span class="line">    HandlerExecutionChain executionChain = getHandlerExecutionChain(handler, request);</span><br><span class="line">    <span class="keyword">if</span> (CorsUtils.isCorsRequest(request)) &#123;</span><br><span class="line">        CorsConfiguration globalConfig = <span class="keyword">this</span>.corsConfigSource.getCorsConfiguration(request);</span><br><span class="line">        CorsConfiguration handlerConfig = getCorsConfiguration(handler, request);</span><br><span class="line">        CorsConfiguration config = (globalConfig != <span class="keyword">null</span> ? globalConfig.combine(handlerConfig) : handlerConfig);</span><br><span class="line">        executionChain = getCorsHandlerExecutionChain(request, executionChain, config);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> executionChain;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Look up a handler for the given request, returning &#123;<span class="doctag">@code</span> null&#125; if no</span></span><br><span class="line"><span class="comment"> * specific one is found. This method is called by &#123;<span class="doctag">@link</span> #getHandler&#125;;</span></span><br><span class="line"><span class="comment"> * a &#123;<span class="doctag">@code</span> null&#125; return value will lead to the default handler, if one is set.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;On CORS pre-flight requests this method should return a match not for</span></span><br><span class="line"><span class="comment"> * the pre-flight request but for the expected actual request based on the URL</span></span><br><span class="line"><span class="comment"> * path, the HTTP methods from the "Access-Control-Request-Method" header, and</span></span><br><span class="line"><span class="comment"> * the headers from the "Access-Control-Request-Headers" header thus allowing</span></span><br><span class="line"><span class="comment"> * the CORS configuration to be obtained via &#123;<span class="doctag">@link</span> #getCorsConfigurations&#125;,</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;Note: This method may also return a pre-built &#123;<span class="doctag">@link</span> HandlerExecutionChain&#125;,</span></span><br><span class="line"><span class="comment"> * combining a handler object with dynamically determined interceptors.</span></span><br><span class="line"><span class="comment"> * Statically specified interceptors will get merged into such an existing chain.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> request current HTTP request</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the corresponding handler instance, or &#123;<span class="doctag">@code</span> null&#125; if none found</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> Exception if there is an internal error</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">abstract</span> Object <span class="title">getHandlerInternal</span><span class="params">(HttpServletRequest request)</span> <span class="keyword">throws</span> Exception</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Build a &#123;<span class="doctag">@link</span> HandlerExecutionChain&#125; for the given handler, including</span></span><br><span class="line"><span class="comment"> * applicable interceptors.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;The default implementation builds a standard &#123;<span class="doctag">@link</span> HandlerExecutionChain&#125;</span></span><br><span class="line"><span class="comment"> * with the given handler, the handler mapping's common interceptors, and any</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@link</span> MappedInterceptor&#125;s matching to the current request URL. Interceptors</span></span><br><span class="line"><span class="comment"> * are added in the order they were registered. Subclasses may override this</span></span><br><span class="line"><span class="comment"> * in order to extend/rearrange the list of interceptors.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;&lt;b&gt;<span class="doctag">NOTE:</span>&lt;/b&gt; The passed-in handler object may be a raw handler or a</span></span><br><span class="line"><span class="comment"> * pre-built &#123;<span class="doctag">@link</span> HandlerExecutionChain&#125;. This method should handle those</span></span><br><span class="line"><span class="comment"> * two cases explicitly, either building a new &#123;<span class="doctag">@link</span> HandlerExecutionChain&#125;</span></span><br><span class="line"><span class="comment"> * or extending the existing chain.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;For simply adding an interceptor in a custom subclass, consider calling</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@code</span> super.getHandlerExecutionChain(handler, request)&#125; and invoking</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@link</span> HandlerExecutionChain#addInterceptor&#125; on the returned chain object.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> handler the resolved handler instance (never &#123;<span class="doctag">@code</span> null&#125;)</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> request current HTTP request</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the HandlerExecutionChain (never &#123;<span class="doctag">@code</span> null&#125;)</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #getAdaptedInterceptors()</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> HandlerExecutionChain <span class="title">getHandlerExecutionChain</span><span class="params">(Object handler, HttpServletRequest request)</span> </span>&#123;</span><br><span class="line">    HandlerExecutionChain chain = (handler <span class="keyword">instanceof</span> HandlerExecutionChain ?</span><br><span class="line">            (HandlerExecutionChain) handler : <span class="keyword">new</span> HandlerExecutionChain(handler));</span><br><span class="line">    String lookupPath = <span class="keyword">this</span>.urlPathHelper.getLookupPathForRequest(request);</span><br><span class="line">    <span class="keyword">for</span> (HandlerInterceptor interceptor : <span class="keyword">this</span>.adaptedInterceptors) &#123;</span><br><span class="line">        <span class="keyword">if</span> (interceptor <span class="keyword">instanceof</span> MappedInterceptor) &#123;</span><br><span class="line">            MappedInterceptor mappedInterceptor = (MappedInterceptor) interceptor;</span><br><span class="line">            <span class="keyword">if</span> (mappedInterceptor.matches(lookupPath, <span class="keyword">this</span>.pathMatcher)) &#123;</span><br><span class="line">                chain.addInterceptor(mappedInterceptor.getInterceptor());</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            chain.addInterceptor(interceptor);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> chain;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>以上是我整理出来的相关方法。</p>
<p>在 getHandler 方法中，我们看到第10行开头就将获取handler的任务交给了抽象方法，待子类实现。</p>
<p>其次，第12行代码告诉我们，我们可以在初始化时向 HandlerMapping 设置一个默认handler，这个以后再讲。</p>
<p>在第18行到第21行代码中，判断如果handler是String类型的，则会从web应用上下文中获取对应的bean。</p>
<p>在第22行代码中，调用了 getHandlerExecutionChain 方法，还记得前一小节中讲的 MappedInterceptor 这个类吗？它就是在这里使用的。也就是说，AbstractHandlerMapping 拥有上下文中所有的 HandlerInterceptor ，但是在处理一次请求时，会只让符合规则的 HandlerInterceptor 参与拦截。</p>
<p>第23行到第28行代码是处理跨域请求的，以后讲到跨域时，我们再来详细看看。</p>
<h4 id="3-3-3-AbstractHandlerMapping-小结"><a href="#3-3-3-AbstractHandlerMapping-小结" class="headerlink" title="3.3.3 AbstractHandlerMapping 小结"></a>3.3.3 AbstractHandlerMapping 小结</h4><p>AbstractHandlerMapping 抽象类还是比较简单的。通过第2章和第3章，我们发现<code>DispatcherServlet</code>中拿到的时执行链 HandlerExecutionChain，会先调用执行链的预处理方法，再通过适配器调用执行链里的handler，再调用后处理方法，等处理完视图渲染后最后调用完成触发方法。为什么有 AbstractHandlerMapping 抽象类？我们发现他负责了 HandlerInterceptor 的初始化和构造成为 HandlerExecutionChain。而更复杂的handler生成就交给了子类。</p>
<h3 id="3-4-AbstractUrlHandlerMapping-解析"><a href="#3-4-AbstractUrlHandlerMapping-解析" class="headerlink" title="3.4 AbstractUrlHandlerMapping 解析"></a>3.4 AbstractUrlHandlerMapping 解析</h3><img src="http://www.plantuml.com/plantuml/svg/HOx12i8m38RlVOg0bmdp3KHG4EP158SFa6sXcvIsfjaKn7UtRDtC8Gdauykli0h2M0liqt9dKw1j3F4PlU-iXezI46i3b-f1aMJd927f4CbjAHpXF44xQ1V928rjDIiqpOQJ5MAB9Yj4V4ay698RFNiAyT4qro0jkrU0uxicBvspIJQuhecGxa9q95ysvO2UpHMbdVFCSHRNWT26HPZ3oHZIQ4f1eVyVzLK_">


<p>在图3-1中，我们发现 AbstractHandlerMapping 只有两个子类，分别是 AbstractUrlHandlerMapping 和 AbstractHandlerMethodMapping。咱们就从最简单的 AbstractUrlHandlerMapping 抽象类开始吧。</p>
<h4 id="3-4-1-AbstractUrlHandlerMapping-初始化分析"><a href="#3-4-1-AbstractUrlHandlerMapping-初始化分析" class="headerlink" title="3.4.1 AbstractUrlHandlerMapping 初始化分析"></a>3.4.1 AbstractUrlHandlerMapping 初始化分析</h4><p>纵览 AbstractUrlHandlerMapping 类，发现这个类并没有初始化方法，虽是抽象类，但是并没有强制需要子类重写的方法，也是一个奇葩了。但实际上并不奇葩，来看一下我总结的初始化方法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Register the specified handler for the given URL path.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> urlPath the URL the bean should be mapped to</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> handler the handler instance or handler bean name String</span></span><br><span class="line"><span class="comment"> * (a bean name will automatically be resolved into the corresponding handler bean)</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> BeansException if the handler couldn't be registered</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> IllegalStateException if there is a conflicting handler registered</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">registerHandler</span><span class="params">(String urlPath, Object handler)</span> <span class="keyword">throws</span> BeansException, IllegalStateException </span>&#123;</span><br><span class="line">    Assert.notNull(urlPath, <span class="string">"URL path must not be null"</span>);</span><br><span class="line">    Assert.notNull(handler, <span class="string">"Handler object must not be null"</span>);</span><br><span class="line">    Object resolvedHandler = handler;</span><br><span class="line">    <span class="comment">// Eagerly resolve handler if referencing singleton via name.</span></span><br><span class="line">    <span class="keyword">if</span> (!<span class="keyword">this</span>.lazyInitHandlers &amp;&amp; handler <span class="keyword">instanceof</span> String) &#123;</span><br><span class="line">        String handlerName = (String) handler;</span><br><span class="line">        <span class="keyword">if</span> (getApplicationContext().isSingleton(handlerName)) &#123;</span><br><span class="line">            resolvedHandler = getApplicationContext().getBean(handlerName);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    Object mappedHandler = <span class="keyword">this</span>.handlerMap.get(urlPath);</span><br><span class="line">    <span class="keyword">if</span> (mappedHandler != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (mappedHandler != resolvedHandler) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(</span><br><span class="line">                    <span class="string">"Cannot map "</span> + getHandlerDescription(handler) + <span class="string">" to URL path ["</span> + urlPath +</span><br><span class="line">                    <span class="string">"]: There is already "</span> + getHandlerDescription(mappedHandler) + <span class="string">" mapped."</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (urlPath.equals(<span class="string">"/"</span>)) &#123;</span><br><span class="line">            <span class="keyword">if</span> (logger.isInfoEnabled()) &#123;</span><br><span class="line">                logger.info(<span class="string">"Root mapping to "</span> + getHandlerDescription(handler));</span><br><span class="line">            &#125;</span><br><span class="line">            setRootHandler(resolvedHandler);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (urlPath.equals(<span class="string">"/*"</span>)) &#123;</span><br><span class="line">            <span class="keyword">if</span> (logger.isInfoEnabled()) &#123;</span><br><span class="line">                logger.info(<span class="string">"Default mapping to "</span> + getHandlerDescription(handler));</span><br><span class="line">            &#125;</span><br><span class="line">            setDefaultHandler(resolvedHandler);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">this</span>.handlerMap.put(urlPath, resolvedHandler);</span><br><span class="line">            <span class="keyword">if</span> (logger.isInfoEnabled()) &#123;</span><br><span class="line">                logger.info(<span class="string">"Mapped URL path ["</span> + urlPath + <span class="string">"] onto "</span> + getHandlerDescription(handler));</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这个类的作用是保存URI和handler的对应关系，在父类调用重写的 getHandlerInternal 方法时，通过request中的URI查找最合适的handler。那URI和handler关系从哪来？当然是通过注册得来的。AbstractUrlHandlerMapping 应该是允许子类在初始化时，调用 registerHandler 方法来注册handler。</p>
<h4 id="3-4-2-AbstractUrlHandlerMapping-处理请求分析"><a href="#3-4-2-AbstractUrlHandlerMapping-处理请求分析" class="headerlink" title="3.4.2 AbstractUrlHandlerMapping 处理请求分析"></a>3.4.2 AbstractUrlHandlerMapping 处理请求分析</h4><p>处理请求那是相当简单，前一小节不是注册了URI和handler的映射关系吗？处理请求就是直接取映射值，映射值好取吗？不带正则的话当然好取，带正则后那就稍微复杂一点。直接看代码吧。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Look up a handler for the URL path of the given request.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> request current HTTP request</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the handler instance, or &#123;<span class="doctag">@code</span> null&#125; if none found</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> Object <span class="title">getHandlerInternal</span><span class="params">(HttpServletRequest request)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    String lookupPath = getUrlPathHelper().getLookupPathForRequest(request);</span><br><span class="line">    Object handler = lookupHandler(lookupPath, request);</span><br><span class="line">    <span class="keyword">if</span> (handler == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="comment">// We need to care for the default handler directly, since we need to</span></span><br><span class="line">        <span class="comment">// expose the PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE for it as well.</span></span><br><span class="line">        Object rawHandler = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">if</span> (<span class="string">"/"</span>.equals(lookupPath)) &#123;</span><br><span class="line">            rawHandler = getRootHandler();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (rawHandler == <span class="keyword">null</span>) &#123;</span><br><span class="line">            rawHandler = getDefaultHandler();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (rawHandler != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="comment">// Bean name or resolved handler?</span></span><br><span class="line">            <span class="keyword">if</span> (rawHandler <span class="keyword">instanceof</span> String) &#123;</span><br><span class="line">                String handlerName = (String) rawHandler;</span><br><span class="line">                rawHandler = getApplicationContext().getBean(handlerName);</span><br><span class="line">            &#125;</span><br><span class="line">            validateHandler(rawHandler, request);</span><br><span class="line">            handler = buildPathExposingHandler(rawHandler, lookupPath, lookupPath, <span class="keyword">null</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (handler != <span class="keyword">null</span> &amp;&amp; logger.isDebugEnabled()) &#123;</span><br><span class="line">        logger.debug(<span class="string">"Mapping ["</span> + lookupPath + <span class="string">"] to "</span> + handler);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span> (handler == <span class="keyword">null</span> &amp;&amp; logger.isTraceEnabled()) &#123;</span><br><span class="line">        logger.trace(<span class="string">"No handler mapping found for ["</span> + lookupPath + <span class="string">"]"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> handler;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Look up a handler instance for the given URL path.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;Supports direct matches, e.g. a registered "/test" matches "/test",</span></span><br><span class="line"><span class="comment"> * and various Ant-style pattern matches, e.g. a registered "/t*" matches</span></span><br><span class="line"><span class="comment"> * both "/test" and "/team". For details, see the AntPathMatcher class.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;Looks for the most exact pattern, where most exact is defined as</span></span><br><span class="line"><span class="comment"> * the longest path pattern.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> urlPath URL the bean is mapped to</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> request current HTTP request (to expose the path within the mapping to)</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the associated handler instance, or &#123;<span class="doctag">@code</span> null&#125; if not found</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #exposePathWithinMapping</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> org.springframework.util.AntPathMatcher</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> Object <span class="title">lookupHandler</span><span class="params">(String urlPath, HttpServletRequest request)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="comment">// Direct match?</span></span><br><span class="line">    Object handler = <span class="keyword">this</span>.handlerMap.get(urlPath);</span><br><span class="line">    <span class="keyword">if</span> (handler != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="comment">// Bean name or resolved handler?</span></span><br><span class="line">        <span class="keyword">if</span> (handler <span class="keyword">instanceof</span> String) &#123;</span><br><span class="line">            String handlerName = (String) handler;</span><br><span class="line">            handler = getApplicationContext().getBean(handlerName);</span><br><span class="line">        &#125;</span><br><span class="line">        validateHandler(handler, request);</span><br><span class="line">        <span class="keyword">return</span> buildPathExposingHandler(handler, urlPath, urlPath, <span class="keyword">null</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// Pattern match?</span></span><br><span class="line">    List&lt;String&gt; matchingPatterns = <span class="keyword">new</span> ArrayList&lt;String&gt;();</span><br><span class="line">    <span class="keyword">for</span> (String registeredPattern : <span class="keyword">this</span>.handlerMap.keySet()) &#123;</span><br><span class="line">        <span class="keyword">if</span> (getPathMatcher().match(registeredPattern, urlPath)) &#123;</span><br><span class="line">            matchingPatterns.add(registeredPattern);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> (useTrailingSlashMatch()) &#123;</span><br><span class="line">            <span class="keyword">if</span> (!registeredPattern.endsWith(<span class="string">"/"</span>) &amp;&amp; getPathMatcher().match(registeredPattern + <span class="string">"/"</span>, urlPath)) &#123;</span><br><span class="line">                matchingPatterns.add(registeredPattern +<span class="string">"/"</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    String bestPatternMatch = <span class="keyword">null</span>;</span><br><span class="line">    Comparator&lt;String&gt; patternComparator = getPathMatcher().getPatternComparator(urlPath);</span><br><span class="line">    <span class="keyword">if</span> (!matchingPatterns.isEmpty()) &#123;</span><br><span class="line">        Collections.sort(matchingPatterns, patternComparator);</span><br><span class="line">        <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            logger.debug(<span class="string">"Matching patterns for request ["</span> + urlPath + <span class="string">"] are "</span> + matchingPatterns);</span><br><span class="line">        &#125;</span><br><span class="line">        bestPatternMatch = matchingPatterns.get(<span class="number">0</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (bestPatternMatch != <span class="keyword">null</span>) &#123;</span><br><span class="line">        handler = <span class="keyword">this</span>.handlerMap.get(bestPatternMatch);</span><br><span class="line">        <span class="keyword">if</span> (handler == <span class="keyword">null</span>) &#123;</span><br><span class="line">            Assert.isTrue(bestPatternMatch.endsWith(<span class="string">"/"</span>));</span><br><span class="line">            handler = <span class="keyword">this</span>.handlerMap.get(bestPatternMatch.substring(<span class="number">0</span>, bestPatternMatch.length() - <span class="number">1</span>));</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// Bean name or resolved handler?</span></span><br><span class="line">        <span class="keyword">if</span> (handler <span class="keyword">instanceof</span> String) &#123;</span><br><span class="line">            String handlerName = (String) handler;</span><br><span class="line">            handler = getApplicationContext().getBean(handlerName);</span><br><span class="line">        &#125;</span><br><span class="line">        validateHandler(handler, request);</span><br><span class="line">        String pathWithinMapping = getPathMatcher().extractPathWithinPattern(bestPatternMatch, urlPath);</span><br><span class="line">        <span class="comment">// There might be multiple 'best patterns', let's make sure we have the correct URI template variables</span></span><br><span class="line">        <span class="comment">// for all of them</span></span><br><span class="line">        Map&lt;String, String&gt; uriTemplateVariables = <span class="keyword">new</span> LinkedHashMap&lt;String, String&gt;();</span><br><span class="line">        <span class="keyword">for</span> (String matchingPattern : matchingPatterns) &#123;</span><br><span class="line">            <span class="keyword">if</span> (patternComparator.compare(bestPatternMatch, matchingPattern) == <span class="number">0</span>) &#123;</span><br><span class="line">                Map&lt;String, String&gt; vars = getPathMatcher().extractUriTemplateVariables(matchingPattern, urlPath);</span><br><span class="line">                Map&lt;String, String&gt; decodedVars = getUrlPathHelper().decodePathVariables(request, vars);</span><br><span class="line">                uriTemplateVariables.putAll(decodedVars);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            logger.debug(<span class="string">"URI Template variables for request ["</span> + urlPath + <span class="string">"] are "</span> + uriTemplateVariables);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> buildPathExposingHandler(handler, bestPatternMatch, pathWithinMapping, uriTemplateVariables);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// No handler found...</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="3-4-3-AbstractUrlHandlerMapping-小结"><a href="#3-4-3-AbstractUrlHandlerMapping-小结" class="headerlink" title="3.4.3 AbstractUrlHandlerMapping 小结"></a>3.4.3 AbstractUrlHandlerMapping 小结</h4><p>AbstractUrlMapping 的一个子类叫 AbstractUrlHandlerMapping，另一个子类叫 AbstractHandlerMethodMapping。有没有发现猫腻？稍微有点常识的人都会发现 第一个子类是URI与handler对象的映射，第二个子类是handler对象上方法与URI的映射。</p>
<p>为什么这么讲？AbstractUrlHandlerMapping 只存了URI和handler的映射关系，没存URI到方法的关系，那你要是写一个普通类当做handler，那SpringMVC怎么知道要调用handler的哪个方法呢？所以像这种映射的handler必须是继承SpringMVC中特有的类或接口，像开发者常用的有Controllor接口及其实现子类、Servlet实现类等等。</p>
<p>注册URI和handler映射也有讲究，不信来看看它的实现类吧。</p>
<h3 id="3-5-SimpleUrlHandlerMapping-解析"><a href="#3-5-SimpleUrlHandlerMapping-解析" class="headerlink" title="3.5 SimpleUrlHandlerMapping 解析"></a>3.5 SimpleUrlHandlerMapping 解析</h3><img src="http://www.plantuml.com/plantuml/svg/TKrB2i8m4Dtd50DkAkeDH50Ht8YBuW5YEjIHCHacOriGxswiRljsx-y2-voXfeSmNfIFFZQCUl8Y55juEIXOGU7hshH8IpXVxnXi0q_b8hiniO0kKGCKoROYJC4RfRXFqN2mQWvsqzHdsA6F-J04bAyzDcU_fc9BsL3__xcQVfnQUxiF">

<p>前面讲了那么多接口，抽象类，我想大家也都挺晕的，这次终于到了一个我们常见的实现类了。这个类超级简单，3.4节讲到 AbstractUrlHandlerMapping 留了一个 registerHandler 方法吗？来看看这个类是怎么用的。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Calls the &#123;<span class="doctag">@link</span> #registerHandlers&#125; method in addition to the</span></span><br><span class="line"><span class="comment"> * superclass's initialization.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">initApplicationContext</span><span class="params">()</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">    <span class="keyword">super</span>.initApplicationContext();</span><br><span class="line">    registerHandlers(<span class="keyword">this</span>.urlMap);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Register all handlers specified in the URL map for the corresponding paths.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> urlMap Map with URL paths as keys and handler beans or bean names as values</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> BeansException if a handler couldn't be registered</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> IllegalStateException if there is a conflicting handler registered</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">registerHandlers</span><span class="params">(Map&lt;String, Object&gt; urlMap)</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (urlMap.isEmpty()) &#123;</span><br><span class="line">        logger.warn(<span class="string">"Neither 'urlMap' nor 'mappings' set on SimpleUrlHandlerMapping"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">for</span> (Map.Entry&lt;String, Object&gt; entry : urlMap.entrySet()) &#123;</span><br><span class="line">            String url = entry.getKey();</span><br><span class="line">            Object handler = entry.getValue();</span><br><span class="line">            <span class="comment">// Prepend with slash if not already present.</span></span><br><span class="line">            <span class="keyword">if</span> (!url.startsWith(<span class="string">"/"</span>)) &#123;</span><br><span class="line">                url = <span class="string">"/"</span> + url;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// Remove whitespace from handler bean name.</span></span><br><span class="line">            <span class="keyword">if</span> (handler <span class="keyword">instanceof</span> String) &#123;</span><br><span class="line">                handler = ((String) handler).trim();</span><br><span class="line">            &#125;</span><br><span class="line">            registerHandler(url, handler);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>简不简单？只要你在xml配置文件中配置了这个bean，然后给它的 urlMap 属性中设置映射，如果映射的Key忘记带<code>/</code>了，他会帮你自动补上，映射的Value可以是ref引用bean，也可以是bean的name，都随你配置。</p>
<p>这里我给出一个xml配置的demo:</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"simpleController"</span> <span class="attr">class</span>=<span class="string">"com.gavinzh.learn.web.simple.controller.SimpleController"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"urlMap"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">map</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">entry</span> <span class="attr">key</span>=<span class="string">"/simple"</span> <span class="attr">value-ref</span>=<span class="string">"simpleController"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">map</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"order"</span> <span class="attr">value</span>=<span class="string">"0"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="3-6-AbstractDetectingUrlHandlerMapping"><a href="#3-6-AbstractDetectingUrlHandlerMapping" class="headerlink" title="3.6 AbstractDetectingUrlHandlerMapping"></a>3.6 AbstractDetectingUrlHandlerMapping</h3><p>前面的 SimpleUrlHandlerMapping 的确很好用，在xml中的 urlMap 就能看到项目的所有映射。但是，有一个问题会在业务快速增加时困扰你。业务增加了，handler写的越来越多了，不仅得写bean配置，还得在 urlMap 中配置一遍，你说头疼不头疼？</p>
<p>SpringMVC的开发人员可能在某一天的早上坐地铁的时候想到了这个问题，那怎么解决呢？方法很简单，我写一个抽象类，功能和 SimpleUrlHandlerMapping 一样，在初始化时加载handler。那handler配置从哪来？想从哪来从哪来呗，我留一个抽象方法等子类实现不就对了？</p>
<p>是的 AbstractDetectingUrlHandlerMapping 就是干这破事的。来看看我总结的方法吧：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Calls the &#123;<span class="doctag">@link</span> #detectHandlers()&#125; method in addition to the</span></span><br><span class="line"><span class="comment"> * superclass's initialization.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">initApplicationContext</span><span class="params">()</span> <span class="keyword">throws</span> ApplicationContextException </span>&#123;</span><br><span class="line">    <span class="keyword">super</span>.initApplicationContext();</span><br><span class="line">    detectHandlers();</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Register all handlers found in the current ApplicationContext.</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;The actual URL determination for a handler is up to the concrete</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@link</span> #determineUrlsForHandler(String)&#125; implementation. A bean for</span></span><br><span class="line"><span class="comment"> * which no such URLs could be determined is simply not considered a handler.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> org.springframework.beans.BeansException if the handler couldn't be registered</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #determineUrlsForHandler(String)</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">detectHandlers</span><span class="params">()</span> <span class="keyword">throws</span> BeansException </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">        logger.debug(<span class="string">"Looking for URL mappings in application context: "</span> + getApplicationContext());</span><br><span class="line">    &#125;</span><br><span class="line">    String[] beanNames = (<span class="keyword">this</span>.detectHandlersInAncestorContexts ?</span><br><span class="line">            BeanFactoryUtils.beanNamesForTypeIncludingAncestors(getApplicationContext(), Object.class) :</span><br><span class="line">            getApplicationContext().getBeanNamesForType(Object<span class="class">.<span class="keyword">class</span>))</span>;</span><br><span class="line">    <span class="comment">// Take any bean name that we can determine URLs for.</span></span><br><span class="line">    <span class="keyword">for</span> (String beanName : beanNames) &#123;</span><br><span class="line">        String[] urls = determineUrlsForHandler(beanName);</span><br><span class="line">        <span class="keyword">if</span> (!ObjectUtils.isEmpty(urls)) &#123;</span><br><span class="line">            <span class="comment">// URL paths found: Let's consider it a handler.</span></span><br><span class="line">            registerHandler(urls, beanName);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">                logger.debug(<span class="string">"Rejected bean name '"</span> + beanName + <span class="string">"': no URL paths identified"</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Determine the URLs for the given handler bean.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> beanName the name of the candidate bean</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the URLs determined for the bean,</span></span><br><span class="line"><span class="comment"> * or &#123;<span class="doctag">@code</span> null&#125; or an empty array if none</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">protected</span> <span class="keyword">abstract</span> String[] determineUrlsForHandler(String beanName);</span><br></pre></td></tr></table></figure>

<p>啪啪啪，和 SimpleUrlHandlerMapping 是不是一样？都是在初始化时做handler的注册？。</p>
<h3 id="3-7-BeanNameUrlHandlerMapping-分析"><a href="#3-7-BeanNameUrlHandlerMapping-分析" class="headerlink" title="3.7 BeanNameUrlHandlerMapping 分析"></a>3.7 BeanNameUrlHandlerMapping 分析</h3><p>AbstractDetectingUrlHandlerMapping 竟然是抽象类？还要子类通过beanName找到URI？太过分了！！！</p>
<p>SpringMVC的开发人员估计怕被打，于是他们自己写了一个简单的实现类，有多简单？beanName就是URI，别名也是URI，这样简单多了吧？</p>
<p>来看看源码吧</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Checks name and aliases of the given bean for URLs, starting with "/".</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="keyword">protected</span> String[] determineUrlsForHandler(String beanName) &#123;</span><br><span class="line">    List&lt;String&gt; urls = <span class="keyword">new</span> ArrayList&lt;String&gt;();</span><br><span class="line">    <span class="keyword">if</span> (beanName.startsWith(<span class="string">"/"</span>)) &#123;</span><br><span class="line">        urls.add(beanName);</span><br><span class="line">    &#125;</span><br><span class="line">    String[] aliases = getApplicationContext().getAliases(beanName);</span><br><span class="line">    <span class="keyword">for</span> (String alias : aliases) &#123;</span><br><span class="line">        <span class="keyword">if</span> (alias.startsWith(<span class="string">"/"</span>)) &#123;</span><br><span class="line">            urls.add(alias);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> StringUtils.toStringArray(urls);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我来展示一个demo：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">name</span>=<span class="string">"/named"</span> <span class="attr">id</span>=<span class="string">"/named"</span> <span class="attr">class</span>=<span class="string">"com.gavinzh.learn.web.simple.controller.NamedController"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">"org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"</span> <span class="attr">p:order</span>=<span class="string">"0"</span>/&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="3-8-AbstractHandlerMethodMapping-分析"><a href="#3-8-AbstractHandlerMethodMapping-分析" class="headerlink" title="3.8 AbstractHandlerMethodMapping 分析"></a>3.8 AbstractHandlerMethodMapping 分析</h3><p>前面我们分析了 AbstractUrlHandlerMapping 及其实现类，知道了那边用的时URI和handler映射，handler必须是继承或者实现某个类或接口才能用。</p>
<p>麻不麻烦？麻烦！一个URI就得一个类，你说麻烦不麻烦？SpringMVC的开发人员头估计都快被打爆了，怎么办怎么办？一个方法就对应一个URI！灵感就这么产生了。</p>
<h4 id="3-8-1-HandlerMethod-和-MappingRegistry"><a href="#3-8-1-HandlerMethod-和-MappingRegistry" class="headerlink" title="3.8.1 HandlerMethod 和 MappingRegistry"></a>3.8.1 HandlerMethod 和 MappingRegistry</h4><p>想要了解针对方法的 HandlerMapping，就得先了解这两个类。</p>
<img src="http://www.plantuml.com/plantuml/svg/TP3HQeGm44NVynNp0VOF98KAInzMMgoq3wKFeyxQxCP49h6mbFvxHzt2fhW-Q9nxRYvtL6in17X4rrdYakAdx-1RWJpBwmuEng65f-P8ROI6q2Np1ndii8sUpujuEITCCKVazte1wlD8YNh979RFbjAmwNegR-dFo2XculSF6F_E8G7JTap1so_gTko7H57gHwbr7oMEet5zHRq9KQfjR4IGlCx-aHYDTtcjjQIirYrFagfXMA_OUt-QnfIVR3IlQ2UQdI-H1SkWrZ2ntSAleBsavscG1YVRkU5Bq0mApw7mxc3wQIsbePNHXhaYSbBSnOgmUsCJ9Q4zIV-hltcplm00">

<p>简单了解一下就行。先看 HandlerMethod 这个类，这个包含了一个bean对象、创建bean的工厂、bean的类型、方法、桥方法、方法入参类型、另一个HandlerMethod。这个对象精确到了方法，也就是说你拿着这个对象，再加入参，就能反射调用方法了。</p>
<p>再来看看 MappingRegistry，前面虽说 HandlerMethod 精确到了方法，但实际上并没有和URI有任何关系，MappingRegistry 就是实现URI和HandlerMethod的映射的。就有人跟我抬杠，说这个类中map的Key是T泛型，不是URI啊，这么来理解吧，一个请求request过来，携带了什么信息？URI，METHOD等等等等，是的这个T泛型之后可能指的是这一系列的组合，我们提的URI也就是代表一个请求的特征。</p>
<h4 id="3-8-2-AbstractHandlerMethodMapping-初始化分析"><a href="#3-8-2-AbstractHandlerMethodMapping-初始化分析" class="headerlink" title="3.8.2 AbstractHandlerMethodMapping 初始化分析"></a>3.8.2 AbstractHandlerMethodMapping 初始化分析</h4><p>在Spring中，对象都是有生命周期的，所以我们讲了这么多类，都是从初始化开始的。AbstractHandlerMapping 类并没有给子类留一个初始化抽象方法，那咱们就找找别的初始化点吧。下面是我找到的初始化点：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Detects handler methods at initialization.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterPropertiesSet</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    initHandlerMethods();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Scan beans in the ApplicationContext, detect and register handler methods.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #isHandler(Class)</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #getMappingForMethod(Method, Class)</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #handlerMethodsInitialized(Map)</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">initHandlerMethods</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">        logger.debug(<span class="string">"Looking for request mappings in application context: "</span> + getApplicationContext());</span><br><span class="line">    &#125;</span><br><span class="line">    String[] beanNames = (<span class="keyword">this</span>.detectHandlerMethodsInAncestorContexts ?</span><br><span class="line">            BeanFactoryUtils.beanNamesForTypeIncludingAncestors(getApplicationContext(), Object.class) :</span><br><span class="line">            getApplicationContext().getBeanNamesForType(Object<span class="class">.<span class="keyword">class</span>))</span>;</span><br><span class="line">    <span class="keyword">for</span> (String beanName : beanNames) &#123;</span><br><span class="line">        <span class="keyword">if</span> (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) &#123;</span><br><span class="line">            Class&lt;?&gt; beanType = <span class="keyword">null</span>;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                beanType = getApplicationContext().getType(beanName);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">catch</span> (Throwable ex) &#123;</span><br><span class="line">                <span class="comment">// An unresolvable bean type, probably from a lazy bean - let's ignore it.</span></span><br><span class="line">                <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">                    logger.debug(<span class="string">"Could not resolve target class for bean with name '"</span> + beanName + <span class="string">"'"</span>, ex);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (beanType != <span class="keyword">null</span> &amp;&amp; isHandler(beanType)) &#123;</span><br><span class="line">                detectHandlerMethods(beanName);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    handlerMethodsInitialized(getHandlerMethods());</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Look for handler methods in a handler.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> handler the bean name of a handler or a handler instance</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">detectHandlerMethods</span><span class="params">(<span class="keyword">final</span> Object handler)</span> </span>&#123;</span><br><span class="line">    Class&lt;?&gt; handlerType = (handler <span class="keyword">instanceof</span> String ?</span><br><span class="line">            getApplicationContext().getType((String) handler) : handler.getClass());</span><br><span class="line">    <span class="keyword">final</span> Class&lt;?&gt; userType = ClassUtils.getUserClass(handlerType);</span><br><span class="line">    Map&lt;Method, T&gt; methods = MethodIntrospector.selectMethods(userType,</span><br><span class="line">            <span class="keyword">new</span> MethodIntrospector.MetadataLookup&lt;T&gt;() &#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="function"><span class="keyword">public</span> T <span class="title">inspect</span><span class="params">(Method method)</span> </span>&#123;</span><br><span class="line">                    <span class="keyword">return</span> getMappingForMethod(method, userType);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">    <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">        logger.debug(methods.size() + <span class="string">" request handler methods found on "</span> + userType + <span class="string">": "</span> + methods);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span> (Map.Entry&lt;Method, T&gt; entry : methods.entrySet()) &#123;</span><br><span class="line">        Method invocableMethod = AopUtils.selectInvocableMethod(entry.getKey(), userType);</span><br><span class="line">        T mapping = entry.getValue();</span><br><span class="line">        registerHandlerMethod(handler, invocableMethod, mapping);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Whether the given type is a handler with handler methods.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> beanType the type of the bean being checked</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> "true" if this a handler type, "false" otherwise.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">abstract</span> <span class="keyword">boolean</span> <span class="title">isHandler</span><span class="params">(Class&lt;?&gt; beanType)</span></span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Provide the mapping for a handler method. A method for which no</span></span><br><span class="line"><span class="comment"> * mapping can be provided is not a handler method.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> method the method to provide a mapping for</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> handlerType the handler type, possibly a sub-type of the method's</span></span><br><span class="line"><span class="comment"> * declaring class</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the mapping, or &#123;<span class="doctag">@code</span> null&#125; if the method is not mapped</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">abstract</span> T <span class="title">getMappingForMethod</span><span class="params">(Method method, Class&lt;?&gt; handlerType)</span></span>;</span><br></pre></td></tr></table></figure>

<p>实际上还会调用别的初始化方法，但实际上并没有用到，所以就不展示了。</p>
<p>在代码第19行到第38行，会从web应用上下文中获取所有对象，然后 调用 isHandler 方法判断是不是handler，如果是，就调用 detectHandlerMethods 方法选择出可以处理请求的method，并注册到 MappingRegistry 中。</p>
<p>在代码第51行到第56行，又调用了抽象方法 getMappingForMethod 获取可以处理请求的method并包装为泛型T。</p>
<p>在代码第63行，会把泛型T、handler和method注册到 MappingRegistry。</p>
<p>哦了，别的代码不用看了，子类最起码要判断bean是不是handler，还得从方法生成泛型T。</p>
<h4 id="3-8-3-AbstractHandlerMethodMapping-处理请求分析"><a href="#3-8-3-AbstractHandlerMethodMapping-处理请求分析" class="headerlink" title="3.8.3 AbstractHandlerMethodMapping 处理请求分析"></a>3.8.3 AbstractHandlerMethodMapping 处理请求分析</h4><p>在3.3节 AbstractHandlerMapping 分析中，我们知道 HandlerInterceptor 由 AbstractHandlerMapping 添加并管理。留给子类的方法是 getHandlerInternal，用于获取真正的handler。</p>
<p>通过 3.8.2 节初始化分析，其实我们已经知道URI等相关信息和方法的映射是存在 MappingRegistry 中的，那么获取handler肯定也就是从那里获取的了。</p>
<p>猜代码不如看代码，看完代码感觉还不如猜代码，来看代码吧：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Look up a handler method for the given request.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> HandlerMethod <span class="title">getHandlerInternal</span><span class="params">(HttpServletRequest request)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    String lookupPath = getUrlPathHelper().getLookupPathForRequest(request);</span><br><span class="line">    <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">        logger.debug(<span class="string">"Looking up handler method for path "</span> + lookupPath);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">this</span>.mappingRegistry.acquireReadLock();</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        HandlerMethod handlerMethod = lookupHandlerMethod(lookupPath, request);</span><br><span class="line">        <span class="keyword">if</span> (logger.isDebugEnabled()) &#123;</span><br><span class="line">            <span class="keyword">if</span> (handlerMethod != <span class="keyword">null</span>) &#123;</span><br><span class="line">                logger.debug(<span class="string">"Returning handler method ["</span> + handlerMethod + <span class="string">"]"</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span> &#123;</span><br><span class="line">                logger.debug(<span class="string">"Did not find handler method for ["</span> + lookupPath + <span class="string">"]"</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> (handlerMethod != <span class="keyword">null</span> ? handlerMethod.createWithResolvedBean() : <span class="keyword">null</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">finally</span> &#123;</span><br><span class="line">        <span class="keyword">this</span>.mappingRegistry.releaseReadLock();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Look up the best-matching handler method for the current request.</span></span><br><span class="line"><span class="comment"> * If multiple matches are found, the best match is selected.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> lookupPath mapping lookup path within the current servlet mapping</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> request the current request</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the best-matching handler method, or &#123;<span class="doctag">@code</span> null&#125; if no match</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #handleMatch(Object, String, HttpServletRequest)</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #handleNoMatch(Set, String, HttpServletRequest)</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> HandlerMethod <span class="title">lookupHandlerMethod</span><span class="params">(String lookupPath, HttpServletRequest request)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    List&lt;Match&gt; matches = <span class="keyword">new</span> ArrayList&lt;Match&gt;();</span><br><span class="line">    List&lt;T&gt; directPathMatches = <span class="keyword">this</span>.mappingRegistry.getMappingsByUrl(lookupPath);</span><br><span class="line">    <span class="keyword">if</span> (directPathMatches != <span class="keyword">null</span>) &#123;</span><br><span class="line">        addMatchingMappings(directPathMatches, matches, request);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (matches.isEmpty()) &#123;</span><br><span class="line">        <span class="comment">// No choice but to go through all mappings...</span></span><br><span class="line">        addMatchingMappings(<span class="keyword">this</span>.mappingRegistry.getMappings().keySet(), matches, request);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (!matches.isEmpty()) &#123;</span><br><span class="line">        Comparator&lt;Match&gt; comparator = <span class="keyword">new</span> MatchComparator(getMappingComparator(request));</span><br><span class="line">        Collections.sort(matches, comparator);</span><br><span class="line">        <span class="keyword">if</span> (logger.isTraceEnabled()) &#123;</span><br><span class="line">            logger.trace(<span class="string">"Found "</span> + matches.size() + <span class="string">" matching mapping(s) for ["</span> +</span><br><span class="line">                    lookupPath + <span class="string">"] : "</span> + matches);</span><br><span class="line">        &#125;</span><br><span class="line">        Match bestMatch = matches.get(<span class="number">0</span>);</span><br><span class="line">        <span class="keyword">if</span> (matches.size() &gt; <span class="number">1</span>) &#123;</span><br><span class="line">            <span class="keyword">if</span> (CorsUtils.isPreFlightRequest(request)) &#123;</span><br><span class="line">                <span class="keyword">return</span> PREFLIGHT_AMBIGUOUS_MATCH;</span><br><span class="line">            &#125;</span><br><span class="line">            Match secondBestMatch = matches.get(<span class="number">1</span>);</span><br><span class="line">            <span class="keyword">if</span> (comparator.compare(bestMatch, secondBestMatch) == <span class="number">0</span>) &#123;</span><br><span class="line">                Method m1 = bestMatch.handlerMethod.getMethod();</span><br><span class="line">                Method m2 = secondBestMatch.handlerMethod.getMethod();</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(<span class="string">"Ambiguous handler methods mapped for HTTP path '"</span> +</span><br><span class="line">                        request.getRequestURL() + <span class="string">"': &#123;"</span> + m1 + <span class="string">", "</span> + m2 + <span class="string">"&#125;"</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        handleMatch(bestMatch.mapping, lookupPath, request);</span><br><span class="line">        <span class="keyword">return</span> bestMatch.handlerMethod;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> handleNoMatch(<span class="keyword">this</span>.mappingRegistry.getMappings().keySet(), lookupPath, request);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以看到，由于是从泛型T中判断获取 HandlerMethod，复杂度有所提高，不过我们只要知道是从request的各个信息来综合判断就行。</p>
<h3 id="3-9-RequestMappingInfoHandlerMapping-分析"><a href="#3-9-RequestMappingInfoHandlerMapping-分析" class="headerlink" title="3.9 RequestMappingInfoHandlerMapping 分析"></a>3.9 RequestMappingInfoHandlerMapping 分析</h3><p>AbstractHandlerMethodMapping 是一个带泛型的抽象类，其泛型代指是请求特征，而 RequestMappingInfoHandlerMapping 则指定了 RequestMappingInfo 类代替泛型。</p>
<p>这里，我们对 RequestMappingInfo 类做一个了解即可。</p>
<img src="http://www.plantuml.com/plantuml/svg/VP0x3i8m343tdC8Nu0GTMSg0LC49hCI5I8qTyfaGToUeeL9fGyRtz6BBIayO8rpeaIccCtfl-NRYKU2feBm3Z9PnWciAHG2Zesub1ao90iVwmr7Os6I5mLUna7NtdKZfBcPRkvatuW43khsH7zneUa93OHlTPzwe2exPqJRJLRGs36Aotkby5V_FijXUfh8Tw1oJk1_QgPTw0m00">

<p>可以看到，request请求特征在这类中都有体现。</p>
<h3 id="3-10-RequestMappingHandlerMapping-分析"><a href="#3-10-RequestMappingHandlerMapping-分析" class="headerlink" title="3.10 RequestMappingHandlerMapping 分析"></a>3.10 RequestMappingHandlerMapping 分析</h3><p>作为 HandlerMapping的终点，也是最重要的一个类，他与我们使用注解<code>@Controllor</code>和<code>@RequestMapping</code>密切相关。接下来就来了解一下怎么密切相关了。</p>
<h4 id="3-10-1-RequestMappingHandlerMapping-初始化分析"><a href="#3-10-1-RequestMappingHandlerMapping-初始化分析" class="headerlink" title="3.10.1 RequestMappingHandlerMapping 初始化分析"></a>3.10.1 RequestMappingHandlerMapping 初始化分析</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterPropertiesSet</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.config = <span class="keyword">new</span> RequestMappingInfo.BuilderConfiguration();</span><br><span class="line">    <span class="keyword">this</span>.config.setPathHelper(getUrlPathHelper());</span><br><span class="line">    <span class="keyword">this</span>.config.setPathMatcher(getPathMatcher());</span><br><span class="line">    <span class="keyword">this</span>.config.setSuffixPatternMatch(<span class="keyword">this</span>.useSuffixPatternMatch);</span><br><span class="line">    <span class="keyword">this</span>.config.setTrailingSlashMatch(<span class="keyword">this</span>.useTrailingSlashMatch);</span><br><span class="line">    <span class="keyword">this</span>.config.setRegisteredSuffixPatternMatch(<span class="keyword">this</span>.useRegisteredSuffixPatternMatch);</span><br><span class="line">    <span class="keyword">this</span>.config.setContentNegotiationManager(getContentNegotiationManager());</span><br><span class="line">    <span class="keyword">super</span>.afterPropertiesSet();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我在代码中找到了这个初始化点，在这个初始化点里，我们发现对于 RequestMappingInfo 的使用，还得有一个配置文件，才能正常的工作。</p>
<h4 id="3-10-2-RequestMappingHandlerMapping-处理请求分析"><a href="#3-10-2-RequestMappingHandlerMapping-处理请求分析" class="headerlink" title="3.10.2 RequestMappingHandlerMapping 处理请求分析"></a>3.10.2 RequestMappingHandlerMapping 处理请求分析</h4><p>在 3.8.2 节 AbstractHandlerMethodMapping 初始化中，我们知道他会从web应用上下文中获取全部bean，然后判断是不是handler，然后注册到 MappingRegistry 中。它留下了两个抽象方法，一个是判断是不是handler，另一个就是通过方法生成request请求规则的方法。抽象方法全部在这里实现了，也很简单，判断是不是handler就是通过注解判断的，生成request的请求规则则是通过注解中的参数来生成。代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@inheritDoc</span>&#125;</span></span><br><span class="line"><span class="comment"> * Expects a handler to have a type-level @&#123;<span class="doctag">@link</span> Controller&#125; annotation.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">boolean</span> <span class="title">isHandler</span><span class="params">(Class&lt;?&gt; beanType)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> (AnnotatedElementUtils.hasAnnotation(beanType, Controller<span class="class">.<span class="keyword">class</span>) ||</span></span><br><span class="line"><span class="class">            <span class="title">AnnotatedElementUtils</span>.<span class="title">hasAnnotation</span>(<span class="title">beanType</span>, <span class="title">RequestMapping</span>.<span class="title">class</span>))</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Uses method and type-level @&#123;<span class="doctag">@link</span> RequestMapping&#125; annotations to create</span></span><br><span class="line"><span class="comment"> * the RequestMappingInfo.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span> the created RequestMappingInfo, or &#123;<span class="doctag">@code</span> null&#125; if the method</span></span><br><span class="line"><span class="comment"> * does not have a &#123;<span class="doctag">@code</span> <span class="doctag">@RequestMapping</span>&#125; annotation.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #getCustomMethodCondition(Method)</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #getCustomTypeCondition(Class)</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> RequestMappingInfo <span class="title">getMappingForMethod</span><span class="params">(Method method, Class&lt;?&gt; handlerType)</span> </span>&#123;</span><br><span class="line">    RequestMappingInfo info = createRequestMappingInfo(method);</span><br><span class="line">    <span class="keyword">if</span> (info != <span class="keyword">null</span>) &#123;</span><br><span class="line">        RequestMappingInfo typeInfo = createRequestMappingInfo(handlerType);</span><br><span class="line">        <span class="keyword">if</span> (typeInfo != <span class="keyword">null</span>) &#123;</span><br><span class="line">            info = typeInfo.combine(info);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> info;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Delegates to &#123;<span class="doctag">@link</span> #createRequestMappingInfo(RequestMapping, RequestCondition)&#125;,</span></span><br><span class="line"><span class="comment"> * supplying the appropriate custom &#123;<span class="doctag">@link</span> RequestCondition&#125; depending on whether</span></span><br><span class="line"><span class="comment"> * the supplied &#123;<span class="doctag">@code</span> annotatedElement&#125; is a class or method.</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #getCustomTypeCondition(Class)</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@see</span> #getCustomMethodCondition(Method)</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> RequestMappingInfo <span class="title">createRequestMappingInfo</span><span class="params">(AnnotatedElement element)</span> </span>&#123;</span><br><span class="line">    RequestMapping requestMapping = AnnotatedElementUtils.findMergedAnnotation(element, RequestMapping<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">    RequestCondition&lt;?&gt; condition = (element <span class="keyword">instanceof</span> Class&lt;?&gt; ?</span><br><span class="line">            getCustomTypeCondition((Class&lt;?&gt;) element) : getCustomMethodCondition((Method) element));</span><br><span class="line">    <span class="keyword">return</span> (requestMapping != <span class="keyword">null</span> ? createRequestMappingInfo(requestMapping, condition) : <span class="keyword">null</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Create a &#123;<span class="doctag">@link</span> RequestMappingInfo&#125; from the supplied</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@link</span> RequestMapping <span class="doctag">@RequestMapping</span>&#125; annotation, which is either</span></span><br><span class="line"><span class="comment"> * a directly declared annotation, a meta-annotation, or the synthesized</span></span><br><span class="line"><span class="comment"> * result of merging annotation attributes within an annotation hierarchy.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> RequestMappingInfo <span class="title">createRequestMappingInfo</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">        RequestMapping requestMapping, RequestCondition&lt;?&gt; customCondition)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> RequestMappingInfo</span><br><span class="line">            .paths(resolveEmbeddedValuesInPatterns(requestMapping.path()))</span><br><span class="line">            .methods(requestMapping.method())</span><br><span class="line">            .params(requestMapping.params())</span><br><span class="line">            .headers(requestMapping.headers())</span><br><span class="line">            .consumes(requestMapping.consumes())</span><br><span class="line">            .produces(requestMapping.produces())</span><br><span class="line">            .mappingName(requestMapping.name())</span><br><span class="line">            .customCondition(customCondition)</span><br><span class="line">            .options(<span class="keyword">this</span>.config)</span><br><span class="line">            .build();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="3-11-小结"><a href="#3-11-小结" class="headerlink" title="3.11 小结"></a>3.11 小结</h3><p>对于 HandlerMapping 接口，其中只有一个方法就是getHandler，返回的是执行链即包含handler和一组拦截器一个对象。</p>
<p>AbstractHandlerMapping 很棒，帮开发者初始化加载了拦截器，然后为生成的执行链注入符合匹配规则的拦截器，把生成handler的任务交给子类。</p>
<p>然而 AbstractHandlerMapping 有两个子类，分别是 AbstractUrlHandlerMapping 和 AbstractHandlerMethodMapping。</p>
<p>AbstractUrlHandlerMapping 抽象类允许子类向String-&gt;Object的map中注册URI和对象的handler。旗下有两个最终实现类，SimpleUrlHandlerMapping 实现类需要在xml配置中显式设置URI和handler的对应关系，而 BeanNameUrlHandlerMapping 实现类只需要在xml中配置上，然后将handler配置的name或者id设置成以<code>/</code>开头即可自动注入。</p>
<p>AbstractHandlerMethodMapping 抽象类则是以方法为处理请求核心，为了实现以方法为中心的handler映射，他提供了一个 MappingRegistry 属性，初始化加载所有bean，允许子类判断其是不是handler，然后由子类生成请求规则。它的唯一最终实现类是 RequestMappingHandlerMapping，也就是我们用的<code>@Controllor</code>和<code>@RequestMapping</code>注解所对应的映射器。</p>
<p>对于 BeanNameUrlHandlerMapping 和 RequestMappingHandlerMapping，只需要在xml配置上bean即可，不需要再配置URI和handler的映射规则。</p>
<p>看到这里，你是不是有点恍然大悟的感觉？handler原来是这么来的，我们自己也可以自定义handler，只要配上自己adpater不就可以了？说对了，下一章我们将来分析 HandlerAdpater 及其实现类。</p>

      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Gavin Zhang
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://blog.gavinzh.com/2018/08/12/learn-springmvc-code-2/" title="SpringMVC 解毒2">http://blog.gavinzh.com/2018/08/12/learn-springmvc-code-2/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag"># java</a>
          
            <a href="/tags/springmvc/" rel="tag"># springmvc</a>
          
            <a href="/tags/spring/" rel="tag"># spring</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/08/12/learn-springmvc-code-1/" rel="next" title="SpringMVC 解毒1">
                <i class="fa fa-chevron-left"></i> SpringMVC 解毒1
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/08/12/learn-springmvc-code-3/" rel="prev" title="SpringMVC 解毒3">
                SpringMVC 解毒3 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="https://avatars3.githubusercontent.com/u/5567916" alt="Gavin Zhang">
            
              <p class="site-author-name" itemprop="name">Gavin Zhang</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">129</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">158</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/jiangmitiao" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:me at gavinzh.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#3-HandlerMapping"><span class="nav-number">1.</span> <span class="nav-text">3 HandlerMapping</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-HandlerExecutionChain-对象"><span class="nav-number">1.1.</span> <span class="nav-text">3.1 HandlerExecutionChain 对象</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-HandlerMapping接口分析"><span class="nav-number">1.2.</span> <span class="nav-text">3.2 HandlerMapping接口分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-3-AbstractHandlerMapping-解析"><span class="nav-number">1.3.</span> <span class="nav-text">3.3 AbstractHandlerMapping 解析</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3-3-1-AbstractHandlerMapping-初始化解析"><span class="nav-number">1.3.1.</span> <span class="nav-text">3.3.1 AbstractHandlerMapping 初始化解析</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-3-2-AbstractHandlerMapping-执行请求分析"><span class="nav-number">1.3.2.</span> <span class="nav-text">3.3.2 AbstractHandlerMapping 执行请求分析</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-3-3-AbstractHandlerMapping-小结"><span class="nav-number">1.3.3.</span> <span class="nav-text">3.3.3 AbstractHandlerMapping 小结</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-4-AbstractUrlHandlerMapping-解析"><span class="nav-number">1.4.</span> <span class="nav-text">3.4 AbstractUrlHandlerMapping 解析</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3-4-1-AbstractUrlHandlerMapping-初始化分析"><span class="nav-number">1.4.1.</span> <span class="nav-text">3.4.1 AbstractUrlHandlerMapping 初始化分析</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-4-2-AbstractUrlHandlerMapping-处理请求分析"><span class="nav-number">1.4.2.</span> <span class="nav-text">3.4.2 AbstractUrlHandlerMapping 处理请求分析</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-4-3-AbstractUrlHandlerMapping-小结"><span class="nav-number">1.4.3.</span> <span class="nav-text">3.4.3 AbstractUrlHandlerMapping 小结</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-5-SimpleUrlHandlerMapping-解析"><span class="nav-number">1.5.</span> <span class="nav-text">3.5 SimpleUrlHandlerMapping 解析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-6-AbstractDetectingUrlHandlerMapping"><span class="nav-number">1.6.</span> <span class="nav-text">3.6 AbstractDetectingUrlHandlerMapping</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-7-BeanNameUrlHandlerMapping-分析"><span class="nav-number">1.7.</span> <span class="nav-text">3.7 BeanNameUrlHandlerMapping 分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-8-AbstractHandlerMethodMapping-分析"><span class="nav-number">1.8.</span> <span class="nav-text">3.8 AbstractHandlerMethodMapping 分析</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3-8-1-HandlerMethod-和-MappingRegistry"><span class="nav-number">1.8.1.</span> <span class="nav-text">3.8.1 HandlerMethod 和 MappingRegistry</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-8-2-AbstractHandlerMethodMapping-初始化分析"><span class="nav-number">1.8.2.</span> <span class="nav-text">3.8.2 AbstractHandlerMethodMapping 初始化分析</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-8-3-AbstractHandlerMethodMapping-处理请求分析"><span class="nav-number">1.8.3.</span> <span class="nav-text">3.8.3 AbstractHandlerMethodMapping 处理请求分析</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-9-RequestMappingInfoHandlerMapping-分析"><span class="nav-number">1.9.</span> <span class="nav-text">3.9 RequestMappingInfoHandlerMapping 分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-10-RequestMappingHandlerMapping-分析"><span class="nav-number">1.10.</span> <span class="nav-text">3.10 RequestMappingHandlerMapping 分析</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3-10-1-RequestMappingHandlerMapping-初始化分析"><span class="nav-number">1.10.1.</span> <span class="nav-text">3.10.1 RequestMappingHandlerMapping 初始化分析</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-10-2-RequestMappingHandlerMapping-处理请求分析"><span class="nav-number">1.10.2.</span> <span class="nav-text">3.10.2 RequestMappingHandlerMapping 处理请求分析</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-11-小结"><span class="nav-number">1.11.</span> <span class="nav-text">3.11 小结</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2013 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Gavin Zhang</span>

  

  
</div>





<div>
	<a href="http://www.beian.miit.gov.cn/" target="_blank">陕ICP备17010002号-1</a>
</div>





        




  <script type="text/javascript">
    (function() {
      var hm = document.createElement("script");
      hm.src = "//tajs.qq.com/stats?sId=61868582";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1261805793&web_id=1261805793" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>





  



  






  













  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/fastclick/1.0.6/fastclick.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/velocity/2.0.5/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/velocity/2.0.5/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.0.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.0.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.0.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.0.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.0.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.0.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.0.0"></script>



  


  

    
      <script id="dsq-count-scr" src="https://zhang-hengs-website-blog.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'http://blog.gavinzh.com/2018/08/12/learn-springmvc-code-2/';
          this.page.identifier = '2018/08/12/learn-springmvc-code-2/';
          this.page.title = 'SpringMVC 解毒2';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://zhang-hengs-website-blog.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  














  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("EhAMmIXTRGtethTcgYwA9afH-gzGzoHsz", "jzP1TaBhMleAUgPLXyB0h8oQ");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=6.0.0"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=6.0.0"></script>


  

</body>
</html>
